// 导入api接口
import { cpList, delImgDriveCost, driveCostAdd, driveCostDelete, driveCostDetailDelete, driveCostDownExl, driveCostImgList, driveCostInsert, driveCostList, driveCostUpdate, sjList, systemGoodsList, systemGoodsTypeList } from '@/api/api'
import { dateRevert, imgFilter } from '@/utils/businessTools'
import configJs from '@/utils/configJs'
import { DateDiff } from '@/utils/tools'
import defaultData from './data'
var data = JSON.parse(JSON.stringify(defaultData))
function notNull(arr) {return arr.reduce((total,item) => {total = true/*total && (item !== '' && item !== null)*/;return total},true)} // 判断数组元素都不为null或''
function plusArr(arr) {return arr.reduce((total,item) => {total = Number(total) + Number(item);return total},0)}
function isDate(arr) {return arr.reduce((total,item) => {total = total && (typeof item == 'string' && item.length > 7);return total},true)}
var adapter = {
	data,
	methods: {
		// ...mapActions(['logOut']),
		/**
		 * 初始化
		 */
		initPage(){
			//还原页面对象
			configJs.revert(data, defaultData);
			this.recordSearchObj[0].zc = this.$store.state.app.navcp; // 写入公共车牌号
		},
		
		/**
		 * 查询员工列表
		 */
		async search(val) {
			if (!this.$store.getters.pageAuth.authoritySearch) {
				return
			}
			this.revertActive() // 重置选择行
			let params = {...this.recordSearchObj[0]}
			// 处理时间
			params.cfrq = dateRevert(params.cfrq)
			params.hcrq = dateRevert(params.hcrq)
			typeof val != 'number' && (val = 1)
			params.page = val
			const res = await driveCostList(params)
			if (res.code === 0) {
				this.oldList = res.data.list // 保存原本list
				this.page = this.tabelHandle(res.data)
				this.pageTotal = res.total
				window.testList = {...this.page.list[0]}
				for (let i in window.testList) {
					window.testList[i] = ''
				}
			} else {
				this.$message(res.msg)
			}
		},

		spanMethod({ row, column, rowIndex, columnIndex }) {
			let arr = [0,1,2,3,4,5,6,7,8,11,12,14,15,16,18,37,38,39,40,41,42,43,44,45,46]
			if (arr.indexOf(columnIndex) > -1) {
				if (row.hasOwnProperty('first')) {
					return {
						rowspan: row.detailLength,
						colspan: 1
					}
				} else if (row.hasOwnProperty('other')) {
					return {
						rowspan: 0,
						colspan: 0
					}
				}
			}
		},

		/**
		 * 处理表格
		 */
		tabelHandle(page) {
			let list = page.list
			let listnew = []
			let key = 0 // 生成后数据的角标
			for(let i = 0; i < list.length; i++) { // 遍历原有list
				let grop = list[i]
				let index = i
				if (grop.details.length > 0) { // 如果包含子项，就遍历子项
					let firstKey = key
					for (let j = 0; j < grop.details.length; j++) {
						let item = {...grop}
						item.key = key // 带上角标
						key++ // 角标自增
						item.detailIndex = j // 标记detail index
						item.editIndex = j // 标记edit index,用于编辑
						item.detailLength = grop.details.length // 标记detail长度
						item.firstKey = firstKey // 标记第一条的角标
						if (j == 0) { // 第一个子项做上first标记
							item.first = true
						} else { // 其他子项做上other标记
							item.other = true
						}
						for (let k in grop.details[j]) { // 将子项带上父项字段，单独为一项
							if (k == 'id') { // 原有子项id改为did带上
								item['did'] = grop.details[j][k]
							} else {
								item[k] = grop.details[j][k]
							}
						}
						item.index = index // 带上原list中index
						item.details = [] // 清掉detail
						listnew.push(item)
					}
				} else { // 不包含子项，就直接写入
					grop.editIndex = 0 // 标记edit index,用于编辑
					grop.key = key // 带上角标
					key++ // 角标自增
					grop.index = index // 带上原list中index
					listnew.push(grop)
				}
			}
			let pagenew = {...page}
			pagenew.list = listnew
			return pagenew
		},

		/**
		 * 刷新
		 */
		async refresh() {
			this.recordSearchObj = [{...this.listExample,cfrq:['',''],hcrq:['','']}]
			this.search()
		},

		/**
		 * 插入
		 */
		insert() {
			if (this.activeRecord.id) {
				this.insertVisi = true
				let oldList = JSON.parse(JSON.stringify(this.oldList))
				for (let i = 0; i < oldList.length; i++) {
					if (oldList[i].id == this.activeRecord.id) {
						let newDetail = {...this.detailExample}
						newDetail.pid = this.activeRecord.id
						newDetail.isAdd = true
						oldList[i].details.push(newDetail)
						break;
					}
				}
				let newPage = {...this.page}
				newPage.list = oldList
				this.page = this.tabelHandle(newPage)


			} else {
				this.$message('请选中行')
			}
		},

		async insertClick() {
			let detail = this.page.list.reduce((total, item) => {
				if (item.isAdd) {
					total = item
				}
				return total
			},{})
			let minorKey = this.minorKey
			let detail1 = {}
			for (let i in detail) {
				if (i == 'id') {
					detail1['pid'] = detail[i]
				} else if (i == 'did') {
					continue
				} else {
					if (minorKey.indexOf(i) > -1) {
						detail1[i] = detail[i]
					}
				}
			}
			const res = await driveCostInsert(detail1)
			if (res.code == 0) {
			this.$message('插入成功')
			this.insertVisi = false
			} else {
			this.$message(res.msg)
			}
		},

		insertCancel() {
			this.insertVisi = false
				let oldList = JSON.parse(JSON.stringify(this.oldList))
				let newPage = {...this.page}
				newPage.list = oldList
				this.page = this.tabelHandle(newPage)
		},

		/**
		 * 增加
		 */
		add() {
			this.resetAdd()
			this.addVisi = true
		},

		/**
		 * 重置增加弹窗
		 */
		resetAdd() {
			this.addRecord = [{...this.listExample}]
		},

		addObjMake(o) {
			let rtObj = {details:[{...this.detailExample}]}
			let mainKey = this.mainKey
			let minorKey = this.minorKey
			for (let i in o) {
				if (mainKey.indexOf(i) > -1) {
					rtObj[i] = o[i]
				} else if (minorKey.indexOf(i) > -1) {
					if (i == 'did') {
						continue
					} else {
						rtObj.details[0][i] = o[i]
					}
				}
			}
			return rtObj
		},

		/**
		 * 增加点击
		 */
		async addClick() {
			// const valid = await this.$refs['addStaff'].validate() // 校验
			// if(valid) {
				let params = this.addObjMake(this.addRecord[0])
				const res = await driveCostAdd(params)
				if (res.code === 0) {
					this.$message('添加成功')
					this.addVisi = false
					this.search()
				} else {
					this.$message(res.msg)
				}
			// }
		},

		addListComputed(record) {
			console.log('addListComputed')
			// 计算往返天数
			let cfrq = record.cfrq
			let hcrq = record.hcrq
			let wfts = record.wfts
			console.log([cfrq,hcrq])
			if (isDate([cfrq,hcrq])) {
				wfts = DateDiff(cfrq,hcrq)
			}
			record.wfts = wfts
			// 计算油数
			let yj = record.yj // 油价
			let yf = record.yf // 油费
			let ys = record.ys // 油数
			if (yj && yf) {
				ys = (yf / yj).toFixed(2)
			}
			record.ys = ys
			// 计算主车截止里程
			let zcqslc = record.zcqslc
			let zcbclc = record.zcbclc
			let zcjzlc = record.zcjzlc
			if (notNull([zcqslc,zcbclc])) {
				zcjzlc = plusArr([zcqslc,zcbclc])
			}
			this.$set(record,'zcjzlc',zcjzlc)
			// 计算挂车截止里程
			let gcqslc = record.gcqslc
			let gcbclc = record.gcbclc
			let gcjzlc = record.gcjzlc
			if (notNull([gcqslc,gcbclc])) {
				gcjzlc = plusArr([gcqslc,gcbclc])
			}
			this.$set(record,'gcjzlc',gcjzlc)
			// 计算费用小计
			yf = record.yf
			let shf = record.shf
			let zsf = record.zsf
			let tcf = record.tcf
			let kzf = record.kzf
			let jsf = record.jsf
			let dhf = record.dhf
			let qtf = record.qtf
			let fyxj = record.fyxj
			if (notNull([yf,shf,zsf,tcf,kzf,jsf,dhf,qtf])) {
				let fee = plusArr([yf,shf,zsf,tcf,kzf,jsf,dhf,qtf])
				fyxj = fee
			}
			record.fyxj = fyxj
			// 计算工资小计
			let lcgz = record.lcgz
			let zhgz = record.zhgz
			let qtgz = record.qtgz
			let gzxj = record.gzxj
			if (notNull([lcgz,zhgz,qtgz])) {
				let fee = plusArr([lcgz,zhgz,qtgz])
				gzxj = fee
			}
			record.gzxj = gzxj
			// 计算补贴小计
			let czbt = record.czbt
			let qtbt = record.qtbt
			let btxj = record.btxj
			if (notNull([czbt,qtbt])) {
				let fee = plusArr([czbt,qtbt])
				btxj = fee
			}
			record.btxj = btxj
			// 计算出车总费用
			fyxj = record.fyxj
			gzxj = record.gzxj
			btxj = record.btxj
			let cczfy = record.cczfy
			if (notNull([fyxj,gzxj,btxj])) {
				let fee = plusArr([fyxj,gzxj,btxj])
				cczfy = fee
			}
			record.cczfy = cczfy
			// 计算结余费用
			let sfyf = record.sfyf
			let hcyf = record.hcyf
			cczfy = record.cczfy
			let jyfy = record.jyfy
			if (notNull([sfyf,hcyf,cczfy])) {
				jyfy = plusArr([sfyf,hcyf]) - Number(cczfy)
			}
			this.$set(record,'jyfy',jyfy)
		},

		addComputed() {
			this.addListComputed(this.addRecord[0])
		},

		addComputedZcbclc(val,row) {
			row.bczclc = val
			this.addComputed()
		},

		addComputedGcbclc(val,row) {
			row.bcgclc = val
			this.addComputed()
		},

		insertComputed() {
			let insertRecord = {}
			for (let i = 0; i < this.page.list.length; i++) {
				if (this.page.list[i].isAdd) {
					insertRecord = this.page.list[i]
					break
				}
			}
			this.insertListComputed(insertRecord)
		},

		/**
		 * 增加、修改计算
		 */
		insertListComputed(record) {
			// 计算油数
			let yj = record.yj // 油价
			let yf = record.yf // 油费
			let ys = '' // 油数
			if (yj && yf) {
				ys = (yf / yj).toFixed(2)
			}
			record.ys = ys
			// 计算费用小计
			let shf = record.shf
			let zsf = record.zsf
			let tcf = record.tcf
			let kzf = record.kzf
			let jsf = record.jsf
			let dhf = record.dhf
			let qtf = record.qtf
			let fyxj = ''
			if (notNull([yf,shf,zsf,tcf,kzf,jsf,dhf,qtf])) {
				let fee = plusArr([yf,shf,zsf,tcf,kzf,jsf,dhf,qtf])
				fyxj = fee
			}
			record.fyxj = fyxj
			// 计算工资
			let lcgz = record.lcgz
			let zhgz = record.zhgz
			let qtgz = record.qtgz
			let gzxj = ''
			if (notNull([lcgz,zhgz,qtgz])) {
				let fee = plusArr([lcgz,zhgz,qtgz])
				gzxj = fee
			}
			record.gzxj = gzxj
			// 计算补贴
			let czbt = record.czbt
			let qtbt = record.qtbt
			let btxj = ''
			if (notNull([czbt,qtbt])) {
				let fee = plusArr([czbt,qtbt])
				btxj = fee
			}
			record.btxj = btxj
			// 计算总费用
			let cczfy = ''
			if (notNull([fyxj,btxj])) {
				let fee = fyxj - btxj
				cczfy = fee
			}
			record.cczfy = cczfy
		},
		
		editComputed() {
			this.editListComputed(this.editRecord)
		},

		editListComputed(records) {
			// 计算往返天数
			let record = records[0] // 第一条
			let cfrq = record.cfrq
			let hcrq = record.hcrq
			let wfts = record.wfts
			if (isDate([cfrq,hcrq])) {
				wfts = DateDiff(cfrq,hcrq)
			}
			record.wfts = wfts
			// 计算油数
			for (let i = 0; i < records.length; i++) {
				let item = records[i]
				let yj = item.yj // 油价
				let yf = item.yf // 油费
				let ys = item.ys // 油数
				if (yj && yf) {
					ys = (yf / yj).toFixed(2)
				}
				item.ys = ys
			}
			// 计算主车截止里程
			let zcqslc = record.zcqslc
			let zcbclc = record.zcbclc
			let zcjzlc = record.zcjzlc
			if (notNull([zcqslc,zcbclc])) {
				zcjzlc = plusArr([zcqslc,zcbclc])
			}
			this.$set(record,'zcjzlc',zcjzlc)
			// 计算挂车截止里程
			let gcqslc = record.gcqslc
			let gcbclc = record.gcbclc
			let gcjzlc = record.gcjzlc
			if (notNull([gcqslc,gcbclc])) {
				gcjzlc = plusArr([gcqslc,gcbclc])
			}
			this.$set(record,'gcjzlc',gcjzlc)
			// 计算费用小计
			for (let i = 0; i < records.length; i++) {
				let item = records[i]
				let yf = item.yf
				let shf = item.shf
				let zsf = item.zsf
				let tcf = item.tcf
				let kzf = item.kzf
				let jsf = item.jsf
				let dhf = item.dhf
				let qtf = item.qtf
				let fyxj = item.fyxj
				if (notNull([yf,shf,zsf,tcf,kzf,jsf,dhf,qtf])) {
					let fee = plusArr([yf,shf,zsf,tcf,kzf,jsf,dhf,qtf])
					fyxj = fee
				}
				item.fyxj = fyxj
			}
			// 计算工资小计
			for (let i = 0; i < records.length; i++) {
				let item = records[i]
				let lcgz = item.lcgz
				let zhgz = item.zhgz
				let qtgz = item.qtgz
				let gzxj = item.gzxj
				if (notNull([lcgz,zhgz,qtgz])) {
					let fee = plusArr([lcgz,zhgz,qtgz])
					gzxj = fee
				}
				item.gzxj = gzxj
			}
			// 计算补贴小计
			for (let i = 0; i < records.length; i++) {
				let item = records[i]
				let czbt = item.czbt
				let qtbt = item.qtbt
				let btxj = item.btxj
				if (notNull([czbt,qtbt])) {
					let fee = plusArr([czbt,qtbt])
					btxj = fee
				}
				item.btxj = btxj
			}
			// 计算出车总费用
			let fyxjArr = records.reduce((total,item) => {total.push(item.fyxj);return total},[])
			let gzxjArr = records.reduce((total,item) => {total.push(item.gzxj);return total},[])
			let btxjArr = records.reduce((total,item) => {total.push(item.btxj);return total},[])
			let cczfy = record.cczfy
			if (notNull([...fyxjArr,...gzxjArr,...btxjArr])) {
				let fee = plusArr([...fyxjArr,...gzxjArr,...btxjArr])
				cczfy = fee
			}
			record.cczfy = cczfy
			// 计算结余费用
			let sfyf = record.sfyf
			let hcyf = record.hcyf
			cczfy = record.cczfy
			let jyfy = record.jyfy
			if (notNull([sfyf,hcyf,cczfy])) {
				jyfy = plusArr([sfyf,hcyf]) - Number(cczfy)
			}
			this.$set(record,'jyfy',jyfy)
		},

		 /**
			* 修改
		  */
		edit() {
			if (this.activeRecord.id) {
				this.editRecord = this.page.list.filter(item => {
					if (item.index === this.activeRecord.index) {
						return true
					}
				})
				this.editVisi = true
			} else {
				this.$message('请选中行')
			}
		},

		/**
		 * 日期转换
		 */
		dateFormat(date) {
			if ('' === date) {
				return date
			} else {
				if (typeof date == 'String') {
					let arr = date.split('_')
					return arr
				} else {
					if (Array.isArray(date) && date.length == 2) {
						return date[0] + '_' + date[1]
					} else {
						return date
					}
				}
			}
		},

		/**
		 * 修改点击
		 */
		async editClick() {
			let obj = this.makeEditObj(this.editRecord)
			console.log(obj)
			const res = await driveCostUpdate(obj)
			if (res.code === 0) {
				this.$message('修改成功')
				this.editVisi = false
				this.search()
			} else {
				this.$message(res.msg)
			}
		},

		/**
		 * 生成edit提交对象
		 */
		makeEditObj(arr) {
			let mainKey = this.mainKey
			let minorKey = this.minorKey
			let obj = {details:[]}
			if (arr.length == 1) {
				if (arr[0].detailLength) { // 只有一条detail的情况
					let sortObj = sort(arr[0])
					obj = {...sortObj.main}
					obj.details = [{...sortObj.minor}]
				} else { // 没有detail的情况
					obj = arr[0]
				}
			} else { // 有多条detail的情况
				let sortObj0 = sort(arr[0])
				obj = {...sortObj0.main}
				obj.details = []
				for(let i = 0; i < arr.length; i++) {
					let sortObj = sort(arr[i])
					obj.details.push(sortObj.minor)
				}
			}

			function sort(o) {
				let rtObj = {main:{},minor:{}}
				for (let i in o) {
					if (mainKey.indexOf(i) > -1) {
						rtObj.main[i] = o[i]
					} else if (minorKey.indexOf(i) > -1) {
						if (i == 'did') {
							rtObj.minor['id'] = o[i]
						} else {
							rtObj.minor[i] = o[i]
						}
					}
				}
				return rtObj
			}
			return obj
		},

		/**
		 * 删除
		 */
		async deleteClick() {
			if (!this.activeRecord.id) {
				this.$message('请选中行')
				return
			}
			let id = this.activeRecord.id
			await this.$confirm('确认删除?', '', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning'
			})
			const res = await driveCostDelete(id)
			if (res.code === 0) {
				this.$message('修改成功')
				this.editVisi = false
				this.search()
			} else {
				this.$message(res.msg)
			}
		},

		/**
		 * 删除详情
		 */
		async deleteDetailClick(id) {
			await this.$confirm('确认删除?', '', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning'
			})
			const res = await driveCostDetailDelete(id)
			if (res.code === 0) {
				this.$message('修改成功')
				this.search()
			} else {
				this.$message(res.msg)
			}
		},

		/**
		 * 点击行
		 */
		rowClick(row, column, e) {
			if (row.key != this.activeRecord.key) {
				this.activeRecord = row
				this.getImgList()
			}
		},

		/**
		 * 重置选择行
		 */
		revertActive() {
			this.activeRecord = {
				id:'',
				ckmc: '',
				wzlb: '',
				wzmc: '',
				gg: '',
				pdr: '',
				pdsj: '',
				dqzmkcsl: '',
				pdkcsl: '',
				pdcysl: '',
				pdzt: '',
				dj: '',
				pdykje: '',
				bz: '',
			}
			this.activeImgList = []
		},

		/**
		 * 日期选择
		 */
		 datePick() {
			 console.error('datepick')
			 console.log(arguments)
			 return 1
		 },

		/**
		 * 物资列表
		 */
		async getGoodsList() {
			const res = await systemGoodsList()
			if (res.code === 0) {
			  this.goodsList = res.data.list
			} else {
			}
		},

		/**
		 * 物资类别列表
		 */
		async getGoodsTypeList() {
			const res = await systemGoodsTypeList()
			if (res.code === 0) {
			  this.goodstypeList = res.data.list
			} else {
			}
		},

		/**
		 * 车牌列表
		 */
		 async getListCp() {
			const res = await cpList()
			if (res.code === 0) {
			  this.cpList = res.data.list
			} else {
				this.$message(res.msg)
			}
		},

		/**
		 * 司机列表
		 */
		 async getListSj() {
			const res = await sjList()
			if (res.code === 0) {
			  this.sjList = res.data.list
			} else {
				this.$message(res.msg)
			}
		},

		/**
		 * 获取图片列表
		 */
		async getImgList() {
			const res = await driveCostImgList(this.activeRecord.id)
			if (res.code === 0) {
				this.activeImgList = imgFilter(res.data.list)
			}
		},

		/**
		 * 删除图片
		 */
		async imgDel(fileName) {
			await this.$confirm('确认删除?', '', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning'
			})
			const res = await delImgDriveCost(fileName)
			if (res.code === 0) {
				this.$message('删除成功')
				this.getImgList()
			} else {
				this.$message(res.msg)
			}
		},

		/**
		 * 下载excel
		 */
		 async downloadExl() {
			driveCostDownExl()
		},
	},
	computed: {
	}
}
export default adapter
